import {
  createRouter,
  createWebHistory,
  createWebHashHistory
} from 'vue-router'

const routes = [{
  path: '/',
  redirect: '/home'
}, {
  path: '/home',
  name: 'home',
  component: () => import("@/views/home/Home.vue"),
}, {
  path: '/login',
  name: 'login',
  component: () => import("@/views/login/Login.vue"),
}, {
  path: '/register',
  name: 'register',
  component: () => import("@/views/register/Register.vue")
}, {
  path: '/myself',
  name: 'myself',
  component: () => import("@/views/myself/MySelf.vue")
}, {
  path: '/shop-car',
  name: 'shop-car',
  component: () => import("@/views/shopping/ShopCar.vue")
}, {
  path: '/order',
  name: 'order',
  component: () => import("@/views/order/Order.vue")
}, {
  path: '/ress',
  name: 'ress',
  component: () => import("@/views/ress/Ress.vue")
}, {
  path: '/shop/:id',
  name: 'shop',
  component: () => import("@/views/shop/Shop.vue")
}]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  const {
    isLogin
  } = localStorage
  if (!isLogin) {
    if (to.name === 'login' || to.name === 'register') {
      next()
    } else {
      router.push({
        name: 'login'
      })
    }
  } else {
    if (to.name === 'login' || to.name === 'register') {
      router.push({
        name: 'home'
      })
    } else {
      next()
    }
  }
})

export default router